<?php
//内容管理相关函数

/**
 * tags自动处理
 * @param string $taglist tags标签，以,分隔
 * @param int $aid 文档id
 */
function autotags($taglist="",$aid=0,$typeid=0,$channelid=0){
    if(!$aid || !is_numeric($aid)){
        return false;
    }
    $tagsM=D('Tags');
    $arctagM=D('Arctag');
    if(empty($taglist)){
        $arctagM->where(array("aid"=>$aid))->delete();//清空指定aid的arctag记录
        return true;
    }
    $taglist=explode(",",$taglist);//将taglist解析成数组
    $tagids=array();//tagid集合
    foreach($taglist as $tag){
        $re=$tagsM->where(array("tagname"=>$tag))->find();//检测tag是否已存在
        if(!$re){
            $tagid=$tagsM->data(array("tagname"=>$tag,"addtime"=>time()))->add();//不存在则添加新tag，并获取tagid
            $tagids[]=$tagid;
        }else{
            $tagids[]=$re['id'];
        }
    }
    
    $arctagM_re=$arctagM->field("tid")->where(array("aid"=>$aid))->select();//获取当前文档的所有tag记录
    $arctagids=array();
    foreach($arctagM_re as $v){
        $arctagids[]=$v['tid'];
    }
    $clearids=array_diff($arctagids,$tagids);//待删除的tagid
    $addids=array_diff($tagids,$arctagids);//带添加的tagid
    $arctagM->where(array("tid"=>array("in",$clearids),"aid"=>$aid))->delete();//清除多余的arctag记录
    $addalldata=array();
    foreach($addids as $etid){
        $addalldata[]=array(
            "tid"=>$etid,
            "aid"=>$aid,
            "typeid"=>$typeid,
            "channelid"=>$channelid,
            "addtime"=>time()
        );
    }
    $arctagM->addAll($addalldata);
    return true;
}

/**
 * 删除一个文档
 * @param int $aid 文档主表id
 * @param string $err 记录错误
 * @return bool
 */
function delArc($aid,&$err){
    $M=M();
    $dbpre=C('DB_PREFIX');//数据表前缀
    $result=$M->query("select arc.id,arc.channelid,ch.addtable from {$dbpre}arctiny as arc left join {$dbpre}channel as ch on ch.id=arc.channelid where arc.id='{$aid}' limit 1");
    if($result===FALSE){
        $err="查询文档失败，文档不存在,".$M->getDbError();
        return FALSE;
    }
    $arcinfo=$result[0];//取得文档基本信息
    if(!empty($arcinfo)){
        $M->startTrans();
        $re=$M->execute("delete from {$dbpre}arctiny where id={$aid}");//删除主表记录,返回受影响的行数
        if($re===FALSE){
            $M->rollback();//回滚事务
            $err="主表删除失败".$M->getDbError();
            return FALSE;
        }
        $re=$M->execute("delete from {$arcinfo['addtable']} where aid={$aid}");//删除附加表记录，返回受影响行数
        if($re===FALSE){
            $M->rollback();//回滚事务
            $err="附加表删除失败".$M->getDbError();
            return FALSE;
        }
        $re=$M->execute("delete from {$dbpre}arctag where aid='{$aid}'");//删除tags记录
        if($re===FALSE){
            $M->rollback();//回滚事务
            $err="arctag表删除失败,".$M->getDbError();
            return FALSE;
        }
        $M->commit();//提交事务
    }
    return true;
}


